import mongoose, { Document, Schema } from 'mongoose';

export interface IProduct extends Document {
  name: string;
  description: string;
  price: number;
  originalPrice: number;
  stock: number;
  images: string[];
  category: mongoose.Types.ObjectId;
  merchant: mongoose.Types.ObjectId;
  brand: string;
  attributes: Record<string, any>;
  specifications: Record<string, any>;
  salesCount: number;
  rating: number;
  reviews: mongoose.Types.ObjectId[];
  isActive: boolean;
  tags: string[];
  createdAt: Date;
  updatedAt: Date;
}

const ProductSchema: Schema = new Schema(
  {
    name: {
      type: String,
      required: [true, '请输入商品名称'],
      trim: true,
    },
    description: {
      type: String,
      required: [true, '请输入商品描述'],
    },
    price: {
      type: Number,
      required: [true, '请输入商品价格'],
      min: [0, '价格不能为负'],
    },
    originalPrice: {
      type: Number,
      min: [0, '原价不能为负'],
    },
    stock: {
      type: Number,
      required: [true, '请输入商品库存'],
      min: [0, '库存不能为负'],
    },
    images: [
      {
        type: String,
      },
    ],
    category: {
      type: Schema.Types.ObjectId,
      ref: 'Category',
      required: [true, '请选择商品分类'],
    },
    merchant: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: [true, '请指定商家'],
    },
    brand: {
      type: String,
      trim: true,
    },
    attributes: {
      type: Map,
      of: Schema.Types.Mixed,
      default: {},
    },
    specifications: {
      type: Map,
      of: Schema.Types.Mixed,
      default: {},
    },
    salesCount: {
      type: Number,
      default: 0,
    },
    rating: {
      type: Number,
      default: 5.0,
      min: 0,
      max: 5,
    },
    reviews: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Review',
      },
    ],
    isActive: {
      type: Boolean,
      default: true,
    },
    tags: [
      {
        type: String,
      },
    ],
  },
  {
    timestamps: true,
  }
);

// 创建索引以提高搜索性能
ProductSchema.index({ name: 'text', description: 'text', brand: 'text', tags: 'text' });
ProductSchema.index({ category: 1 });
ProductSchema.index({ merchant: 1 });
ProductSchema.index({ price: 1 });
ProductSchema.index({ rating: -1 });
ProductSchema.index({ salesCount: -1 });

export default mongoose.model<IProduct>('Product', ProductSchema); 